package com.aia.ilp.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.Assert;

import com.aia.ilp.domain.CALC;
import com.aia.ilp.domain.CALCExample;
import com.aia.ilp.domain.Cust;
import com.aia.ilp.domain.CustExample;
import com.aia.ilp.domain.History;
import com.aia.ilp.domain.HistoryExample;
import com.aia.ilp.domain.Image;
import com.aia.ilp.domain.ImageExample;
import com.aia.ilp.domain.SmsLog;
import com.aia.ilp.domain.SmsLogExample;
import com.aia.ilp.domain.SmsMsgchosend;
import com.aia.ilp.domain.SmsMsgchosendExample;
import com.aia.ilp.domain.Thumb;
import com.aia.ilp.domain.ThumbExample;
import com.aia.ilp.domain.CustExample.Criteria;
import com.aia.ilp.persistence.dao.CALCDAO;
import com.aia.ilp.persistence.dao.CustDAO;
import com.aia.ilp.persistence.dao.HistoryDAO;
import com.aia.ilp.persistence.dao.ImageDAO;
import com.aia.ilp.persistence.dao.SmsLogDAO;
import com.aia.ilp.persistence.dao.SmsMsgchosendDAO;
import com.aia.ilp.persistence.dao.ThumbDAO;
import com.aia.ilp.web.NewsAction;
import com.aia.ilp.web.NewsitemAction;
import com.aia.ilp.web.PublicUploadAction;
import com.aia.ilp.web.ShowAction;
import com.aia.ilp.web.gift.GetAction;
import com.aia.ilp.web.gift.UpdateAction;
import com.aia.ilp.web.json.CustomerActJson;
import com.aia.ilp.web.json.CustomerCalcJson;
import com.aia.ilp.web.json.CustomerConfirmJson;
import com.aia.ilp.web.json.CustomerGetQuestionJson;
import com.aia.ilp.web.json.CustomerRegJson;
import com.aia.ilp.web.json.CustomerResetPasswordJson;
import com.aia.ilp.web.json.CustomerSmsJson;
import com.aia.ilp.web.json.CustomerVoteJson;
import com.aia.ilp.webinterface.LatestCusts;
import com.aia.ilp.webinterface.TopCusts;
import com.cfh.ahead.Constant;
import com.cfh.ahead.SequenceNameProvider;
import com.cfh.domain.Config;
import com.cfh.domain.ConfigExample;
import com.cfh.domain.ConfigKey;
import com.cfh.domain.Sequence;
import com.cfh.domain.User;
import com.cfh.persistence.dao.ConfigDAO;
import com.cfh.persistence.dao.SequenceDAO;
import com.cfh.persistence.dao.UserDAO;
import com.cfh.util.Tools;
import com.cfh.util.XmlStringBuffer;
import com.cfh.web.PageBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ValidationAware;

public class MainServiceImpl implements MainService {
	/**
	 * Logger for this class
	 */
	//private static final Log logger = LogFactory.getLog(MainServiceImpl.class); 
	//change to log4j
	private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(MainServiceImpl.class);
	
	private static boolean IS_GAME_OVER = true;
	private static final String MSG_GAME_OVER = "本次活动已经结束，非常感谢您的参与。";
	
	private CustDAO custDAO;
	private ImageDAO imageDAO;
	private ThumbDAO thumbDAO;
	private UserDAO userDAO;
	private SmsMsgchosendDAO smsMsgchosendDAO;
	private SmsLogDAO smsLogDAO;
	private HistoryDAO historyDAO;
	private CALCDAO cALCDAO;
	private SequenceDAO sequenceDAO;
	private ConfigDAO configDAO;
	private SequenceNameProvider sequenceNameProvider;

	public int countCust(CustExample example) {

		return custDAO.mm_countByExample(example);
	}

	public Cust custLogin(String username, String password) {
		CustExample example = new CustExample();
		example.createCriteria().andCUST_MAILEqualTo(username).andCUST_PASSWORDEqualTo(password);
		List list = custDAO.selectByExample(example);
		if (list != null && list.size() > 0) {
			if (list.size() > 1) {
				String msg = "custLogin find more than one cust!  :" + username + "," + password;
				logger.error(msg);
				throw new RuntimeException(msg);
			}
			return (Cust) list.get(0);
		} else {
			return null;
		}

	}

	private void ensure(LatestCusts action) {
		if (action.getPageBean() == null) {
			action.setPageBean(new PageBean());
		}
		if (action.getPage() <= 0) {
			action.setPage(1);
		}
		if (action.getPageSize() <= 0) {
			action.setPageSize(6);
		}
		action.getPageBean().setPageRecorders(action.getPageSize());
	}

	public List getActivedCustsByMobile(String mobile) {
		CustExample example = new CustExample();
		example.createCriteria().andCUST_M_ACTIVE_FLGEqualTo("Y").andCUST_MOBILEEqualTo(mobile);
		return custDAO.selectByExample(example);
	}

	public List getAllCustsByMobile(String mobile) {
		CustExample example = new CustExample();
		example.createCriteria().andCUST_MOBILEEqualTo(mobile);
		return custDAO.selectByExample(example);
	}

	public CustDAO getCustDAO() {
		return custDAO;
	}

	public void getGiftStatus(GetAction action) {
		try {
			XmlStringBuffer xsb = new XmlStringBuffer();
			String s = Constant.XML_HEAD_STRING + "<root><code>00</code><message>OK</message></root>";
			action.setXml(s);

			if (!"AIA_ILP_INTERFACE_2011".equals(action.getAuth())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>01</code><message>Invalid auth</message></root>");
				return;
			}
			if (StringUtils.isEmpty(action.getGuid())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>02</code><message>Invalid guid</message></root>");
				return;
			}
			Cust cust = custDAO.selectByPrimaryKey(action.getGuid());
			if (cust == null) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>03</code><message>Not found this user</message></root>");
				return;
			}
			if (!"Y".equals(cust.getCUST_M_ACTIVE_FLG())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>04</code><message>User not actived</message></root>");
				return;
			}
			if (!"Y".equals(cust.getCUST_DREAM_FLG())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>05</code><message>User not public dream</message></root>");
				return;
			}

			if ("Y".equals(cust.getCUST_GIFT_FLG())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>06</code><message>Already got gift</message></root>");
				return;
			}
		} catch (Exception e) {
			// logger.error("第三方接口出错", e);
			throw new RuntimeException(e);
			// String msg = "exception: " + e.toString();
			// action.setXml(Constant.XML_HEAD_STRING +
			// "<root><code>99</code><message>" + msg + "</message></root>");
			// return;
		}

	}

	public HistoryDAO getHistoryDAO() {
		return historyDAO;
	}

	private synchronized Long getHistoryNextId() {
		String sequenceName = sequenceNameProvider.getName(History.class);
		Sequence seq = sequenceDAO.selectByPrimaryKey(sequenceName);
		seq.setNEXTID(new Long(seq.getNEXTID().longValue() + 1L));
		sequenceDAO.updateByPrimaryKey(seq);
		return seq.getNEXTID();
	}

	private synchronized Long getCALCNextId() {
		String sequenceName = sequenceNameProvider.getName(CALC.class);
		Sequence seq = sequenceDAO.selectByPrimaryKey(sequenceName);
		seq.setNEXTID(new Long(seq.getNEXTID().longValue() + 1L));
		sequenceDAO.updateByPrimaryKey(seq);
		return seq.getNEXTID();
	}

	public Image getImage(String mail) {
		return imageDAO.selectByPrimaryKey(mail);
	}

	public Image getImageByMail(String mail) {
		ImageExample example = new ImageExample();
		example.createCriteria().andIMG_MAILEqualTo(mail);
		List list = imageDAO.selectByExampleWithBLOBs(example);
		if (list != null && list.size() > 0)
			return (Image) list.get(0);
		else
			return null;
	}

	public ImageDAO getImageDAO() {
		return imageDAO;
	}

	public SequenceDAO getSequenceDAO() {
		return sequenceDAO;
	}

	public SequenceNameProvider getSequenceNameProvider() {
		return sequenceNameProvider;
	}

	public SmsLogDAO getSmsLogDAO() {
		return smsLogDAO;
	}

	public List getSmslogToday(String mobile) {
		String today = Tools.getToday();
		SmsLogExample example = new SmsLogExample();
		example.createCriteria().andSMSLOG_MOBILEEqualTo(mobile).andSMSLOG_DATEEqualTo(today);
		return smsLogDAO.selectByExample(example);
	}

	public SmsMsgchosendDAO getSmsMsgchosendDAO() {
		return smsMsgchosendDAO;
	}

	public Thumb getThumb(String guid) {
		return thumbDAO.selectByPrimaryKey(guid);
	}

	public Thumb getThumbByMail(String mail) {
		ThumbExample example = new ThumbExample();
		example.createCriteria().andTHUMB_MAILEqualTo(mail);
		List list = thumbDAO.selectByExampleWithBLOBs(example);

		if (list != null && list.size() > 0)
			return (Thumb) list.get(0);
		else
			return null;
	}

	public ThumbDAO getThumbDAO() {
		return thumbDAO;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void insertCustByReg(CustomerRegJson actionSupport) {
		Cust custToReg = actionSupport.getCustToReg();
		// 把mail小写化
		custToReg.setCUST_MAIL(custToReg.getCUST_MAIL().toLowerCase());

		// 把不要的属性清空，保证安全性
		custToReg.setCUST_VOTE(0L);
		custToReg.setCUST_M_ACTIVE_FLG("N");
		custToReg.setCUST_DREAM_FLG("N");
		custToReg.setCUST_DREAM("");
		custToReg.setCUST_M_VARIFY_CODE("");
		custToReg.setCUST_GIFT_FLG("");
		custToReg.setCUST_IMAGE_FLG("");

		// 生成主键
		custToReg.setCUST_GUID(Tools.GUID());
		custToReg.setCUST_DATE(Tools.getToday());
		custToReg.setCUST_TIME(Tools.getTime());

		custDAO.insertSelective(custToReg);
		actionSupport.getSession().put("customer", custToReg);
	}

	private String makeIPAddress() {
		try {
			return ServletActionContext.getRequest().getRemoteAddr();
		} catch (Exception e) {
			logger.warn("makeIPAddress:" + e, e);
			return "";
		}
	}

	public void prepareLatestCusts(Object object) {
		LatestCusts action = null;
		if (object instanceof LatestCusts) {
			action = (LatestCusts) object;
		} else {
			logger.warn("Class cast error when run service");
			return;
		}
		ensure(action);
		CustExample example = new CustExample();
		Criteria c = example.createCriteria();
		c.andCUST_DREAM_FLGEqualTo("Y").andCUST_M_ACTIVE_FLGEqualTo("Y");
		String search = action.getSearch();
		if (!StringUtils.isEmpty(search)) {
			c.andCUST_MAILLike("%" + search.trim() + "%");
		}

		example.setOrderByClause("CUST_DREAM_DATE desc, CUST_DREAM_TIME desc");
		int totalRows = custDAO.mm_countByExample(example);
		action.getPageBean().setTotalRows(totalRows);
		action.getPageBean().setCurrentPage(action.getPage());
		// logger.debug("getStart:"+action.getPageBean().getStart());
		// logger.debug("getLimit:"+action.getPageBean().getLimit());
		List list = custDAO.selectByExample(example, action.getPageBean().getStart(), action.getPageBean().getLimit());
		action.setLatestCusts(list);
	}

	public void prepareTopCusts(Object object) {
		TopCusts topCusts = null;
		if (object instanceof TopCusts) {
			topCusts = (TopCusts) object;
		} else {
			logger.warn("Class cast error when run service");
			return;
		}
		CustExample example = new CustExample();
		example.createCriteria().andCUST_M_ACTIVE_FLGEqualTo("Y").andCUST_DREAM_FLGEqualTo("Y");
		example.setOrderByClause("CUST_VOTE DESC");
		List list = custDAO.selectByExample(example, 0, 10);
		topCusts.setTopCusts(list);
	}

	public void prepareTopCusts() {
		CustExample example = new CustExample();
		example.createCriteria().andCUST_M_ACTIVE_FLGEqualTo("Y").andCUST_DREAM_FLGEqualTo("Y");
		example.setOrderByClause("CUST_VOTE DESC");
		List list = custDAO.selectByExample(example, 0, 10);
		ServletActionContext.getRequest().setAttribute("topCusts", list);
	}

	public void sanityTestdb(ValidationAware action) {
		try {
			User user = userDAO.selectByPrimaryKey("admin");
			action.addActionMessage("测试连接ILP_USER数据表成功");
			if (user == null) {
				action.addActionError("ILP_USER表中无关键数据，请初始化数据");
			}
		} catch (Exception e) {
			logger.error("测试连接ILP_USER数据表失败", e);
			action.addActionError("测试连接ILP_USER数据表失败:" + e);
		}

		try {
			SmsMsgchosendExample example = new SmsMsgchosendExample();
			example.setOrderByClause("MSGSERNO desc");
			List list = smsMsgchosendDAO.selectByExample(example, 0, 10);
			action.addActionMessage("测试连接SMS_MSGCHOSEND数据表成功");
			if (list.size() == 0) {
				action.addActionError("SMS_MSGCHOSEND表中无数据");
			} else {

			}
		} catch (Exception e) {
			logger.error("测试连接SMS_MSGCHOSEND数据表失败", e);
			action.addActionError("测试连接SMS_MSGCHOSEND数据表失败:" + e);
		}
	}

	public void sanityTestnewcustdb(ActionSupport actionSupport) {

		try {
			actionSupport.addActionMessage("开始");
			CustExample example = new CustExample();
			example.createCriteria().andCUST_MAILLike("testilp%aia.com");
			int count = custDAO.mm_countByExample(example);
			if (count > 0) {
				actionSupport.addActionMessage("数据库中存在testilpXXXX@aia.com这样的测试数据, 条数:" + count);
				return;
			} else {
				actionSupport.addActionMessage("准备插入1000条测试数据：testilp1000@aia.com~testilp1030@aia.com");
			}
			for (int i = 0; i < 1000; i++) {
				int ref = 1000 + i;
				long mobile = 13900010000L + ref;
				java.util.Random r = new java.util.Random();
				int vote = r.nextInt(5000);
				Cust record = new Cust();
				record.setCUST_GUID(Tools.GUID());
				record.setCUST_MAIL("testilp" + ref + "@aia.com");
				record.setCUST_PASSWORD("testilp" + ref);
				record.setCUST_BIRTHDAY("19800101");
				record.setCUST_PROVINCE("上海");
				record.setCUST_CITY("上海");
				record.setCUST_COUNTY("长宁区");
				record.setCUST_DREAM("梦想 梦想 梦想");
				record.setCUST_DREAM_FLG("Y");
				record.setCUST_DREAM_DATE(Tools.getToday());
				record.setCUST_DREAM_TIME(Tools.getTime());
				record.setCUST_MOBILE(String.valueOf(mobile));
				record.setCUST_M_ACTIVE_FLG("Y");
				record.setCUST_SECURITY_Q("我最喜欢的明星是");
				record.setCUST_SECURITY_A("孙燕姿");
				record.setCUST_VOTE((long) vote);
				record.setCUST_GIFT_FLG("N");
				record.setCUST_GIFT_DATE(Tools.getToday());
				record.setCUST_GIFT_TIME(Tools.getTime());
				record.setCUST_DATE(Tools.getToday());
				record.setCUST_TIME(Tools.getTime());
				custDAO.insertSelective(record);
			}
		} finally {
			actionSupport.addActionMessage("结束");
		}

	}

	public void sanityTestnewcustdbDelete(ActionSupport actionSupport) {

		try {
			actionSupport.addActionMessage("开始");
			CustExample example = new CustExample();
			example.createCriteria().andCUST_MAILLike("testilp%aia.com");
			int count = custDAO.mm_countByExample(example);
			if (count > 0) {
				actionSupport.addActionMessage("数据库中存在testilpXXXX@aia.com这样的测试数据, 条数:" + count);
				actionSupport.addActionMessage("准备删除测试数据");
				int delCount = custDAO.deleteByExample(example);
				actionSupport.addActionMessage("成功删除测试数据,记录数:" + delCount);
			} else {
				actionSupport.addActionMessage("数据库中不存在testilpXXXX@aia.com这样的测试数据");
				return;
			}
		} finally {
			actionSupport.addActionMessage("结束");
		}

	}

	public void saveImage(Image record) {
		imageDAO.insertSelective(record);
	}

	public void saveThumb(Thumb record) {
		thumbDAO.insertSelective(record);
	}

	public List selectCust(CustExample example, int start, int limit) {
		return custDAO.selectByExample(example, start, limit);
	}

	public void sendSMS(String mobile, String cityCode, String verifyCode, String mail) {
//		// 插入ILP_SMSLOG表
//		SmsLog smslog = new SmsLog();
//		smslog.setSMSLOG_GUID(Tools.GUID());
//		smslog.setSMSLOG_FREETEXT1(cityCode);
//		smslog.setSMSLOG_MAIL(mail);
//		smslog.setSMSLOG_MOBILE(mobile);
//		smslog.setSMSLOG_DATE(Tools.getToday());
//		smslog.setSMSLOG_TIME(Tools.getTime());
//		smsLogDAO.insertSelective(smslog);
//
//		SmsMsgchosend smssend = new SmsMsgchosend();
//		smssend.setMSGCO("0986");
//		smssend.setMSGAGT("000000000");
//		smssend.setMSGPOLN("ILP0000000");
//		smssend.setMSGMSAG01(smsContent(verifyCode));
//		smssend.setMSGMSAG02("");
//		smssend.setMSGMSAG03("");
//		smssend.setMSGTYPE("N");
//		smssend.setMSGNO(1);
//		smssend.setMSGFUNC("T04S01");
//		smssend.setMSGDATE(new Date());
//		smssend.setMSGUSER("eStore_ILP");
//		smssend.setMSGSTS("S");
//		smssend.setMSGMBNUM(mobile);
//		smssend.setMSGFL01("");
//		smssend.setMSGFL02("");
//		smssend.setMSGFL03("");
//		smssend.setMSGFL04(0);
//		// 插入SMS_xxx表
//		smsMsgchosendDAO.insertSelective(smssend);

	}

	public void setCustDAO(CustDAO custDAO) {
		this.custDAO = custDAO;
	}

	public void setHistoryDAO(HistoryDAO historyDAO) {
		this.historyDAO = historyDAO;
	}

	public void setImageDAO(ImageDAO imageDAO) {
		this.imageDAO = imageDAO;
	}

	public void setSequenceDAO(SequenceDAO sequenceDAO) {
		this.sequenceDAO = sequenceDAO;
	}

	public void setSequenceNameProvider(SequenceNameProvider sequenceNameProvider) {
		this.sequenceNameProvider = sequenceNameProvider;
	}

	public void setSmsLogDAO(SmsLogDAO smsLogDAO) {
		this.smsLogDAO = smsLogDAO;
	}

	public void setSmsMsgchosendDAO(SmsMsgchosendDAO smsMsgchosendDAO) {
		this.smsMsgchosendDAO = smsMsgchosendDAO;
	}

	public void setThumbDAO(ThumbDAO thumbDAO) {
		this.thumbDAO = thumbDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void updateCustByAct(CustomerActJson action) {
		String verifyCode = "";
		verifyCode = action.getAct_code();
		Cust loginCust = (Cust) action.getSession().get("customer");
		Cust newCust = custDAO.selectByPrimaryKey(loginCust.getCUST_GUID());
		boolean isUserPowerKey = false;

		// loginCust的非空较验在action中完成了
		{// 验证是否已经是激活的用户
			if ("Y".equals(newCust.getCUST_M_ACTIVE_FLG())) {
				action.addActionError("您的帐号已经激活，不必再次激活");
				return;
			}
		}
		{
			String powerKey = Tools.getProperties("sms.powerkey");
			if (verifyCode.equalsIgnoreCase(powerKey)) {
				isUserPowerKey = true;
			}
		}

		if (isUserPowerKey) {
			action.addActionMessage("使用了万能激活码，您是测试用户!");
			newCust.setCUST_FREEFLG1("Y");
		} else {
			// 查看验证码集中有没有
			String allCode = newCust.getCUST_M_VARIFY_CODE();
			if (allCode == null) {
				allCode = "";
			}

			String[] allCodeArray = allCode.split("\\|");
			List<String> allCodeList = new ArrayList<String>();
			for (String s : allCodeArray) {
				if (!StringUtils.isEmpty(s)) {
					allCodeList.add(s);
				}
			}

			if (!allCodeList.contains(verifyCode)) {
				action.addActionError("较验码输入错误");
				return;
			}
		}

		{// 更新激活标识
			newCust.setCUST_M_ACTIVE_FLG("Y");
			custDAO.updateByPrimaryKeySelective(newCust);
		}
		{// 更新session
			action.getSession().put("customer", newCust);
		}

	}

	public void updateCustSendSMS(CustomerSmsJson action) {
		/*
		String verifyCode = "";
		String verifySms = "";
		int sendCounts = 0;
		Cust loginCust = (Cust) action.getSession().get("customer");
		// action.addActionMessage("该用户手机号为：" + loginCust.getCUST_MOBILE());
		Cust newCust = custDAO.selectByPrimaryKey(loginCust.getCUST_GUID());
		// loginCust的非空较验在action中完成了
		{// 验证是否已经是激活的用户
			if ("Y".equals(newCust.getCUST_M_ACTIVE_FLG())) {
				action.addActionError("您的帐号已经激活，不必发送较验短信");
				return;
			}
		}
		{// 验证次数
			Long sendCountsLongObject = newCust.getCUST_FREENUM1();
			if (sendCountsLongObject == null) {
				sendCounts = 0;
			} else {
				sendCounts = sendCountsLongObject.intValue();
			}
			if (sendCounts >= 3) {
				action.addActionError("该手机号发送短信的次数超过限制");
				return;
			}
			newCust.setCUST_FREENUM1(new Long(sendCounts + 1));
		}
		// OK, 开始发短信
		{// 生成验证码
			verifyCode = Tools.randSixNumberString();
			verifySms = smsContent(verifyCode) ;
		}
		{// 将验证码放在 CUST_M_VARIFY_CODE，并存入数据库
			String allCode = newCust.getCUST_M_VARIFY_CODE();
			if (allCode == null) {
				allCode = "";
			}
			String[] allCodeArray = allCode.split("\\|");
			List<String> allCodeList = new ArrayList<String>();
			for (String s : allCodeArray) {
				if (!StringUtils.isEmpty(s)) {
					allCodeList.add(s);
				}
			}
			allCodeList.add(verifyCode);
			while (allCodeList.size() >= 5) {
				allCodeList.remove(0);
			}
			StringBuffer sb = new StringBuffer();
			for (String item : allCodeList) {
				sb.append(item + "|");
			}
			newCust.setCUST_M_VARIFY_CODE(sb.toString());
			custDAO.updateByPrimaryKeySelective(newCust);
		}

		{// 插入ILP_SMSLOG表
			SmsLog smslog = new SmsLog();
			smslog.setSMSLOG_GUID(Tools.GUID());
			// smslog.setSMSLOG_MAIL(newCust.getCUST_MAIL());
			smslog.setSMSLOG_DATE(Tools.getToday());
			smslog.setSMSLOG_TIME(Tools.getTime());
			smslog.setSMSLOG_FREETEXT1(verifyCode);
			smslog.setSMSLOG_FREETEXT2(newCust.getCUST_GUID());
			smsLogDAO.insertSelective(smslog);
		}

		{// 发短信
			// String smsDebug = Tools.getProperties("sms.show");
			// if ("Y".equals(smsDebug)) {
			// action.addActionMessage("生成验证码:[" + verifyCode + "]");
			// }
			SmsMsgchosend smssend = new SmsMsgchosend();
			smssend.setMSGCO("0986");
			smssend.setMSGAGT("000000000");
			smssend.setMSGPOLN("ILP0000000");
			smssend.setMSGMSAG01(verifySms);
			smssend.setMSGMSAG02("");
			smssend.setMSGMSAG03("");
			smssend.setMSGTYPE("N");
			smssend.setMSGNO(1);
			smssend.setMSGFUNC("T04S01");
			smssend.setMSGDATE(new Date());
			smssend.setMSGUSER("eStore_ILP");
			smssend.setMSGSTS("S");
			smssend.setMSGMBNUM(newCust.getCUST_MOBILE());
			smssend.setMSGFL01("");
			smssend.setMSGFL02("");
			smssend.setMSGFL03("");
			smssend.setMSGFL04(0);
			// 插入SMS_xxx表
			smsMsgchosendDAO.insertSelective(smssend);
		}

		{// 更新session
			action.getSession().put("customer", newCust);
		}
		*/
	}

	public void updateGiftStatus(UpdateAction action) {
		try {
			XmlStringBuffer xsb = new XmlStringBuffer();
			String s = Constant.XML_HEAD_STRING + "<root><code>00</code><message>OK</message></root>";
			action.setXml(s);

			if (!"AIA_ILP_INTERFACE_2011".equals(action.getAuth())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>01</code><message>Invalid auth</message></root>");
				return;
			}
			if (StringUtils.isEmpty(action.getGuid())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>02</code><message>Invalid guid</message></root>");
				return;
			}
			Cust cust = custDAO.selectByPrimaryKey(action.getGuid());
			if (cust == null) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>03</code><message>Not found this user</message></root>");
				return;
			}
			if (!"Y".equals(cust.getCUST_M_ACTIVE_FLG())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>04</code><message>User not actived</message></root>");
				return;
			}
			if (!"Y".equals(cust.getCUST_DREAM_FLG())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>05</code><message>User not public dream</message></root>");
				return;
			}

			if ("Y".equals(cust.getCUST_GIFT_FLG())) {
				action.setXml(Constant.XML_HEAD_STRING + "<root><code>06</code><message>Already got gift</message></root>");
				return;
			}
			Cust custToUpdate = new Cust();
			custToUpdate.setCUST_GIFT_DATE(Tools.getToday());
			custToUpdate.setCUST_GIFT_TIME(Tools.getTime());
			custToUpdate.setCUST_GIFT_FLG("Y");
			CustExample example = new CustExample();
			example.createCriteria().andCUST_GUIDEqualTo(action.getGuid());
			custDAO.updateByExampleSelective(custToUpdate, example);

		} catch (Exception e) {
			// logger.error("第三方接口出错", e);
			throw new RuntimeException(e);
			// String msg = "exception: " + e.toString();
			// action.setXml(Constant.XML_HEAD_STRING +
			// "<root><code>99</code><message>" + msg + "</message></root>");
			// return;
		}

	}

	public void updateverifyCodeForCust(String custGUID, String verifyCode) {
		// TODO Auto-generated method stub

	}

	/********
	 * 投票
	 */
	public void updateVote(CustomerVoteJson action) {
		Cust custTo = null;
		Cust custFrom = (Cust) action.getSession().get("customer");
		String mailFrom = custFrom.getCUST_MAIL();
		String mailTo = action.getMail();
		Assert.hasText(mailFrom);
		boolean isTestUser = false;
		
		{//活动结束了吗？
			if(IS_GAME_OVER){
				action.addActionError(MSG_GAME_OVER);
				return;
			}
		}
		
		{// 
			if ("Y".equals(custFrom.getCUST_FREEFLG1())) {
				action.addActionMessage("(注意：您是测试用户，您的投票已经被记录!)");
				isTestUser = true;
			}
		}
		{// 不能对自己投票
			if (mailFrom.equalsIgnoreCase(mailTo)) {
				action.addActionError("不能对自己投票");
				return;
			}
		}
		{// 查看今天对这个用户投了几票，如果已经投过了则报错
			HistoryExample example = new HistoryExample();
			example.createCriteria().andCUST_DATEEqualTo(Tools.getToday()).andHIS_CUST_MAIL_FROMEqualTo(mailFrom)
					.andHIS_CUST_MAIL_TOEqualTo(mailTo);
			List list = historyDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("今天已经对该用户投过票了，请明天再试");
				return;
			}
		}
		{// 验证被投票者的资格
			CustExample custExample = new CustExample();
			custExample.createCriteria().andCUST_MAILEqualTo(mailTo);
			List clist = custDAO.selectByExample(custExample);
			if (clist == null || clist.size() == 0) {
				action.addActionError("找不到这个用户");
				return;
			}
			custTo = (Cust) clist.get(0);
			if (!"Y".equals(custTo.getCUST_M_ACTIVE_FLG())) {
				action.addActionError("这个用户未激活");
				return;
			}
			if (!"Y".equals(custTo.getCUST_DREAM_FLG())) {
				action.addActionError("这个用户未发表梦想");
				return;
			}
		}

		{// 插入投票历史表
			History history = new History();
			history.setHIS_ID(getHistoryNextId());
			history.setHIS_IP(makeIPAddress());
			history.setHIS_CUST_MAIL_FROM(mailFrom);
			history.setHIS_CUST_MAIL_TO(mailTo);
			history.setBEFORE_VOTE_COUNT(custTo.getCUST_VOTE());
			history.setAFTER_VOTE_COUNT(new Long(custTo.getCUST_VOTE().longValue() + 1L));
			history.setCUST_DATE(Tools.getToday());
			history.setCUST_TIME(Tools.getTime());
			if (isTestUser) {
				history.setHIS_REMARK("TEST_USER");
			}
			historyDAO.insertSelective(history);
			// history.set
		}
		{// 更改票数
			custTo.setCUST_VOTE(new Long(custTo.getCUST_VOTE().longValue() + 1L));
			custDAO.updateByPrimaryKeySelective(custTo);
		}
	}

	/****
	 * 较验邮箱是否已经被注册
	 */
	public void validateEmailExist(CustomerRegJson actionSupport) {
		Cust custToReg = actionSupport.getCustToReg();
		CustExample example = new CustExample();
		example.createCriteria().andCUST_MAILEqualTo(Tools.safe(custToReg.getCUST_MAIL()));
		List custGotItList = custDAO.selectByExample(example);
		if (custGotItList != null && custGotItList.size() > 0) {
			actionSupport.addFieldError("CUST_MOBILE", "该邮箱已经被注册");
		}
		return;
	}

	/****
	 * 较验手机是否已经被注册
	 */
	public void validateMobileExist(CustomerRegJson actionSupport) {
		Cust custToReg = actionSupport.getCustToReg();
		CustExample example = new CustExample();
		example.createCriteria().andCUST_MOBILEEqualTo(Tools.safe(custToReg.getCUST_MOBILE()));
		List custGotItList = custDAO.selectByExample(example);
		if (custGotItList != null && custGotItList.size() > 0) {
			actionSupport.addFieldError("CUST_MOBILE", "该手机号已经被注册");
		}
		return;
	}

	/****
	 * 上传图片更新梦想
	 */
	public void updateDreamPic(PublicUploadAction action) {
		boolean needProcessImg = false;
		Cust loginCust = (Cust) action.getSession().get("customer");
		{// 登录？
			if (loginCust == null) {
				action.addActionError("未登录或者会话超时");
				return;
			}
		}
		
		{//活动结束了吗？
			if(IS_GAME_OVER){
				action.addActionError(MSG_GAME_OVER);
				return;
			}
		}

		Cust newCust = custDAO.selectByPrimaryKey(loginCust.getCUST_GUID());
		File image = action.getImage();
		String imageFilename = action.getImageFileName();
		String mydream = action.getMydream();

		{// 看session与DB中数据一致性
			if (newCust == null) {
				action.addActionError("出错了，可能是帐号被禁用");
				return;
			} else {
				// 把最新状态的Cust放入session
				loginCust = newCust;
				action.getSession().put("customer", newCust);
			}
		}
		{// 是否激活？
			if (!"Y".equals(newCust.getCUST_M_ACTIVE_FLG())) {
				action.addActionError("您的帐号未激活");
				return;
			}
		}
		

		{// 看是否已经发布过梦想
			if ("Y".equals(newCust.getCUST_DREAM_FLG())) {
				action.addActionError("您已经发布过梦想了");
				return;
			}
		}
		{ // 对梦想的安全处理
			mydream = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(mydream);
			mydream = mydream.replaceAll("\r", "");
			mydream = mydream.replaceAll("\n", "");
			mydream = mydream.replaceAll("\r\n", "");
			// 过滤敏感字符
			java.util.regex.Pattern p = java.util.regex.Pattern.compile("<|>|操她|操他|她妈|他妈|共产党|我靠|我日|去死|fuck");
			java.util.regex.Matcher m = p.matcher(mydream);
			if (m.find()) {
				action.addActionError("梦想中含有敏感字符");
				return;
			}
		}
		{// 对梦想的较验
			if (StringUtils.isEmpty(mydream)) {
				action.addActionError("未填写梦想");
				return;
			}
			if (mydream.length() > 140) {
				action.addActionError("梦想内容超过140字符");
				return;
			}
		}

		if (image != null && StringUtils.isNotEmpty(imageFilename)) {
			// 需要处理图片
			needProcessImg = true;
		}
		if (needProcessImg) {
			// 因为可能之前上传过图片， 如果存在就更新，否而就插入图片
			{// 保存大图
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				byte[] thumbBytes = null;
				boolean sucFlg = false;
				try {
					Thumbnails.of(image).size(258, 258).outputFormat("jpg").outputQuality(0.7).toOutputStream(outputStream);
					thumbBytes = outputStream.toByteArray();
					sucFlg = true;
				} catch (net.coobird.thumbnailator.tasks.UnsupportedFormatException e) {
					action.addActionMessage("出错，该文件不是图片文件");
					return;
				} catch (Exception e) {
					logger.error("用户上传图片出错", e);
					action.addActionMessage("出现未知错误，请检查图片格式");
					return;

				}
				if (sucFlg) {
					Image tmpRec = imageDAO.selectByPrimaryKey(newCust.getCUST_GUID());
					if (tmpRec == null) {
						Image myImage = new Image();
						myImage.setIMG_GUID(newCust.getCUST_GUID());
						myImage.setIMG_MAIL(newCust.getCUST_MAIL());
						myImage.setIMG_BIN(thumbBytes);
						imageDAO.insertSelective(myImage);
					} else {
						tmpRec.setIMG_MAIL(newCust.getCUST_MAIL());
						tmpRec.setIMG_BIN(thumbBytes);
						imageDAO.updateByPrimaryKeySelective(tmpRec);
					}
				}
			}

			{// 保存小图
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				byte[] thumbBytes = null;
				boolean sucFlg = false;
				try {
					Thumbnails.of(image).size(92, 92).outputFormat("jpg").outputQuality(0.7).toOutputStream(outputStream);
					thumbBytes = outputStream.toByteArray();
					sucFlg = true;
				} catch (net.coobird.thumbnailator.tasks.UnsupportedFormatException e) {
					action.addActionMessage("出错，该文件不是图片文件");
					return;
				} catch (Exception e) {
					logger.error("用户上传图片出错", e);
					action.addActionMessage("出现未知错误，请检查图片格式");
					return;
				}
				if (sucFlg) {
					Thumb tmpRec = thumbDAO.selectByPrimaryKey(newCust.getCUST_GUID());
					if (tmpRec == null) {
						Thumb myThumb = new Thumb();
						myThumb.setTHUMB_GUID(newCust.getCUST_GUID());
						myThumb.setTHUMB_MAIL(newCust.getCUST_MAIL());
						myThumb.setTHUMB_BIN(thumbBytes);
						thumbDAO.insertSelective(myThumb);
					} else {
						tmpRec.setTHUMB_MAIL(newCust.getCUST_MAIL());
						tmpRec.setTHUMB_BIN(thumbBytes);
						thumbDAO.updateByPrimaryKeySelective(tmpRec);
					}
				}
			}

		}

		{// 更新dream字段
			newCust.setCUST_DREAM(mydream);
			custDAO.updateByPrimaryKeySelective(newCust);
			// 把最新状态的Cust放入session
			action.getSession().put("customer", newCust);
		}

	}

	public void updateCustByConfirm(CustomerConfirmJson action) {
		Cust loginCust = (Cust) action.getSession().get("customer");
		{// 登录？
			if (loginCust == null) {
				action.addActionError("未登录或者会话超时");
				return;
			}
		}
		
		{//活动结束了吗？
			if(IS_GAME_OVER){
				action.addActionError(MSG_GAME_OVER);
				return;
			}
		}

		Cust newCust = custDAO.selectByPrimaryKey(loginCust.getCUST_GUID());
		String mydream = newCust.getCUST_DREAM();

		{// 看session与DB中数据一致性
			if (newCust == null) {
				action.addActionError("出错了，可能是帐号被禁用");
				return;
			} else {
				// 把最新状态的Cust放入session
				loginCust = newCust;
				action.getSession().put("customer", newCust);
			}
		}
		{// 是否激活？
			if (!"Y".equals(newCust.getCUST_M_ACTIVE_FLG())) {
				action.addActionError("您的帐号未激活");
				return;
			}
		}

		{// 看是否已经发布过梦想
			if ("Y".equals(newCust.getCUST_DREAM_FLG())) {
				action.addActionError("您已经发布过梦想了");
				return;
			}
		}
		{ // 对梦想的安全处理
			mydream = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(mydream);
			mydream = mydream.replaceAll("\r", "");
			mydream = mydream.replaceAll("\n", "");
			mydream = mydream.replaceAll("\r\n", "");
			// 过滤敏感字符
			java.util.regex.Pattern p = java.util.regex.Pattern.compile("<|>|操她|操他|她妈|他妈|共产党|我靠|我日|去死|fuck");
			java.util.regex.Matcher m = p.matcher(mydream);
			if (m.find()) {
				action.addActionError("梦想中含有敏感字符");
				return;
			}
		}
		{// 对梦想的较验
			if (StringUtils.isEmpty(mydream)) {
				action.addActionError("未填写梦想");
				return;
			}
			if (mydream.length() > 140) {
				action.addActionError("梦想内容超过140字符");
				return;
			}
		}

		{
			newCust.setCUST_DREAM_FLG("Y");
			newCust.setCUST_DREAM_DATE(Tools.getToday());
			newCust.setCUST_DREAM_TIME(Tools.getTime());
			newCust.setCUST_VOTE(1L);//发表完梦想就有一票
			custDAO.updateByPrimaryKeySelective(newCust);
			action.getSession().put("customer", newCust);
		}

	}

	public void selectCustByShow(ShowAction action) {
		String userMail = action.getUser();
		String newCust = null;
		{// 较验
			if (StringUtils.isEmpty(userMail)) {
				action.addActionError("参数错误");
			} else {
				userMail = userMail.toLowerCase().trim();
				action.setUser(userMail);
			}
		}
		{ //
			CustExample example = new CustExample();
			example.createCriteria().andCUST_MAILEqualTo(userMail);
			List list = custDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.setShowcust((Cust) list.get(0));
			}
		}
	}

	/***
	 * 
	 * 计算结果，如果
	 */
	public void updateCalc(CustomerCalcJson action) {
		// 注意，暂时不启用服务端较验，相信前台JS较验
		CALC record = action.getCalc();
		if (record == null) {
			action.addActionError("传入的值为空");
			return;
		}
		{// 试图拿出session中的CUST。 如果登录则有些不同
			Cust loginCust = (Cust) action.getSession().get("customer");
			if (loginCust != null && StringUtils.isNotEmpty(loginCust.getCUST_GUID())) {
				record.setCALC_REG_FLG("Y");
				record.setCALC_CUST_GUID(loginCust.getCUST_GUID());
				record.setCALC_CUST_MAIL(loginCust.getCUST_MAIL());
				record.setCALC_CUST_NAME(loginCust.getCUST_NAME());
				
				record.setCALC_FREETEXT1(loginCust.getCUST_MOBILE());
				record.setCALC_FREETEXT2(loginCust.getCUST_PROVINCE());
				record.setCALC_FREETEXT3(loginCust.getCUST_CITY());
				record.setCALC_FREETEXT4(loginCust.getCUST_COUNTY());
			} else {
				record.setCALC_REG_FLG("N");
			}
		}
		{ // 开始计算了
			try {
				long result = 0L;
				result = record.getCALC_LIFEPAY()*120 + record.getCALC_LOAN() + record.getCALC_EDU() + record.getCALC_HEALTH();
				record.setCALC_ENSURE_NEED(result);
				record.setCALC_ENSURE_GAP(result - record.getCALC_ENSURE_HAS());
			} catch (Exception e) {
				logger.warn("计算器出错" + e, e);
				action.addActionError("计算时出错，请检查输入的值");
				return;
			}
		}
		{// 其他值初始化
			record.setCALC_DATE(Tools.getToday());
			record.setCALC_TIME(Tools.getTime());
			record.setCALC_ID(getCALCNextId());
			record.setCALC_IP(makeIPAddress());
		
		}
		{
			cALCDAO.insertSelective(record);
			action.getSession().put("mycalc", record);
		}
	}

	public void setcALCDAO(CALCDAO cALCDAO) {
		this.cALCDAO = cALCDAO;
	}

	public CALCDAO getcALCDAO() {
		return cALCDAO;
	}

	public int deleteCustByPrimaryKey(String string) {
		return custDAO.deleteByPrimaryKey(string);
	}

	public void customerGetQuestion(CustomerGetQuestionJson action) {
		Cust cust = action.getCustToReg();
		Cust custFould = null;
		CustExample example = new CustExample();
		example.createCriteria().andCUST_MAILEqualTo(cust.getCUST_MAIL());
		List list = custDAO.selectByExample(example);
		if (list != null && list.size() > 0) {
			custFould = (Cust) list.get(0);
			action.addActionMessage(custFould.getCUST_SECURITY_Q());
			return;
		} else {
			action.addActionError("找不到该用户:" + cust.getCUST_MAIL());
			return;
		}

	}

	public void updateCustomerResetPassword(CustomerResetPasswordJson action) {
		Cust cust = action.getCustToReg();
		Cust custFould = null;
		CustExample example = new CustExample();
		example.createCriteria().andCUST_MAILEqualTo(cust.getCUST_MAIL());
		List list = custDAO.selectByExample(example);
		if (list != null && list.size() > 0) {
			custFould = (Cust) list.get(0);
		} else {
			action.addActionError("找不到该用户:" + cust.getCUST_MAIL());
			return;
		}

		if (StringUtils.isEmpty(cust.getCUST_SECURITY_A())) {
			action.addActionError("未填写答案");
			return;
		}

		if (StringUtils.isEmpty(custFould.getCUST_SECURITY_A())) {
			action.addActionError("注册时未填写答案，请联系管理员");
			return;
		}

		if (StringUtils.isEmpty(cust.getCUST_PASSWORD())) {
			action.addActionError("未输入密码");
			return;
		}

		// 如果答对了就更新密码
		if (cust.getCUST_SECURITY_A().equals(custFould.getCUST_SECURITY_A())) {
			Cust custClone = new Cust();
			custClone.setCUST_PASSWORD(cust.getCUST_PASSWORD());
			custClone.setCUST_GUID(custFould.getCUST_GUID());
			custDAO.updateByPrimaryKeySelective(custClone);
			action.addActionMessage(Tools.safe(custFould.getCUST_MAIL()) + "的密码已经成功更新");
		} else {
			action.addActionError("答案不正确");
			return;
		}
		return;
	}

	public List selectCustByExample(CustExample example) {
		return custDAO.selectByExample(example);
	}

	public List selectCALCByExample(CALCExample example) {
		return cALCDAO.selectByExample(example);
	}

	private String smsContent(String argCode) {
		String s = "";
		if (argCode == null) {
			s = "";
		} else {
			s = argCode;
		}
		return "感谢您的参与，您的手机验证密码为" + s + "";
	}

	public List selectHistoryByExample(HistoryExample example) {
		return historyDAO.selectByExample(example);
	}
	
	private void ensurePageBean(NewsAction action) {
		if (action.getPageBean() == null) {
			action.setPageBean(new PageBean());
		}
		if (action.getPage() <= 0) {
			action.setPage(1);
		}
		if (action.getPageSize() <= 0) {
			action.setPageSize(9);
		}
		action.getPageBean().setPageRecorders(action.getPageSize());
	}

	public void prepareTopNews(NewsAction action) {
		ensurePageBean(action);
		ConfigExample configExample = new ConfigExample();
		configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_NEWS);
		configExample.setOrderByClause(Constant.ORDERBY_NEWS);
		
		int totalRows = configDAO.countByExample(configExample);
		action.getPageBean().setTotalRows(totalRows);
		action.getPageBean().setCurrentPage(action.getPage());
		List list = configDAO.selectByExample(configExample, action.getPageBean().getStart(), action.getPageBean().getLimit());
		action.setTopNews(list);
	}

	public void setConfigDAO(ConfigDAO configDAO) {
		this.configDAO = configDAO;
	}

	public ConfigDAO getConfigDAO() {
		return configDAO;
	}

	public void selectOneNews(NewsitemAction action) {
		Config tmpCfg = null;
		ConfigExample configExample = new ConfigExample();
		configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_NEWS).andCFG_CODEEqualTo(action.getId());
		configExample.setOrderByClause(Constant.ORDERBY_NEWS);
		ConfigKey key = new ConfigKey();
		key.setCFG_CODE(action.getId());
		key.setCFG_TYPE(Constant.CFG_TYPE_NEWS);
		tmpCfg = configDAO.selectByPrimaryKey(key);
		action.setOnenews(tmpCfg);
	}

}
